// pages/search/index.js
const{
  projectList
} =require('../../api/project')
const{
  AddUser
} =require('../../api/user')
const qiniuUploader = require('../../utils/qiniuUploader')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showPopupOptin: false,
    fileList: [],
    option: [],
    username: '',
    phone: '',
    ruleForm: {
      relation: '',
      relation_real: '',
      role_relation: '',
      role_relation_real: '',
    },
    radio: 0,
    project_list: [],
    relationOption: [
      {text:"三里屯养护",value:10},
      {text:"杨庄公园养护",value:11},
      {text:"八里桥主题公园",value:13}
    ],
    typeOption: [
      {text:"区域经理",value:10},{text:"项目经理",value:11},{text:"项目主管",value:12},{text:"技术员",value:13},{text:"领班",value:14}
    ],
    selName:''

  },
  initQiniu() {
    var options = {
      region: 'SCN', // 华北区
      uptokenURL: 'https://api.fudaojiapu.com:8889/qiniu', //请求后端uptoken的url地址
      //uptoken: 'xxx',  //你请求后端的uptoken,和上面一样的，uptokenURL不填就找uptoken,填一个就可以了（这里是字符串数据不是url了）
      domain: 'https://img.fudaojiapu.com', //yourBucketId:这个去你域名配置那里要
      shouldUseQiniuFileName: false,
      //key: '' 
    };
    qiniuUploader.init(options);
  },
  afterRead(event) {
    const { file } = event.detail; // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    this.uploadImg(file);
  },
  delete(event) {
    console.log(event)
    let imgDelIndex = event.detail.index
    let fileList = this.data.fileList
    fileList.splice(imgDelIndex,1)
    console.log('删除图片的',fileList)
    this.setData({
        fileList
    })
  },
  didPressChooesImage(that) {
    initQiniu();
    // 微信 API 选文件
    wx.chooseImage({
        count: 1,
        success: function (res) {
          
        }
      })
  },
  uploadImg(file){
    this.initQiniu();
    let _this=this
    var imgUrl =[];
    // 多张图片上传
    for(var i=0;i<file.length;i++){
      //var filePath = file[i].path;
      var filePath = file[i].path;
          // 交给七牛上传
          qiniuUploader.upload(filePath, (res) => {
            this.setData({
              'imageObject': res
            });
            const { fileList = [] } = this.data;
            fileList.push({ ...file, url: res.imageURL });
            this.setData({fileList})
          }, (error) => {
            console.error('error: ' + JSON.stringify(error));
          },
          null,// 可以使用上述参数，或者使用 null 作为参数占位符
          (progress) => {
              console.log('上传进度', progress.progress)
              console.log('已经上传的数据长度', progress.totalBytesSent)
              console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
          }, cancelTask => this.setData({cancelTask})
          );
    }
  },
  selrelation(e) {
    switch (e.target.dataset.name) {
      case 'relation':
        let tmp_project_list = []
        console.log(this.data.project_list)
        console.log(this.data.ruleForm)
        this.data.project_list.forEach((item) => {
          if (this.data.ruleForm.role_relation_real == 10 && item.area_manager_uid == 0) {
            tmp_project_list.push(item)
          }
          if (this.data.ruleForm.role_relation_real == 11 && item.project_leader_uid == 0) {
            tmp_project_list.push(item)
          }
          if (this.data.ruleForm.role_relation_real == 12 && item.director_uid == 0) {
            tmp_project_list.push(item)
          }
        });
        console.log(tmp_project_list)
        this.data.option = tmp_project_list.map(item => {
          return { text: item.project_name, value: item.id };
        })
        break
      case 'role_relation':
        this.data.option = this.data.typeOption
        break
      case 'industry': // 行业
        if (this.data.ruleForm.type) {
          this.data.option = this.data.ruleForm.type_real.children
        }
        // this.data.option = this.data.industryOption
        break
      default:
    }
    this.data.selName = e.target.dataset.name
    this.setData({
      showPopup: true,
      option: this.data.option
    })
  },
  onCancel() {
    this.setData({
      showPopup: false
    })
  },
  onChange(event) {
    this.setData({
      radio: event.detail,
    });
  },
  onConfirm(event) {
    console.log(this.data.selName)
    console.log(event.detail)
    let arr = this.data.selName.split('.')
    let value =
      typeof event.detail.value == 'string'
        ? event.detail.value
        : event.detail.value.text
    if (arr.length > 1) {
      this.data.ruleForm[arr[0]][arr[1]] = value
    } else {
      if (this.data.selName == 'morecredit') {
        this.data.ruleForm[this.data.selName] += value + ','
      } else if (this.data.selName == 'guarantor.qualification') {
        this.data.ruleForm.guarantor.qualification = value
      } else if (this.data.selName == 'guarantor.credit') {
        this.data.ruleForm.guarantor.credit = value
      } else {
        this.data.ruleForm[this.data.selName] = value
        this.data.ruleForm[this.data.selName+'_real'] = event.detail.value.value
      }
    }
    let ruleForm = this.data.ruleForm
    let showPopup = (this.data.showPopup = false)
    this.setData({ ruleForm, showPopup })
  },
  onChangeName(event) {
    this.setData({
      username: event.detail,
    });
  },
  onChangePhone(event) {
    this.setData({
      phone: event.detail,
    });
  },
  submit(event) {
    console.log(this.data.ruleForm)
    console.log(this.data.fileList)
    console.log(this.data.username)
    console.log(this.data.phone)
    if (this.data.username.length && this.data.phone.length) {
      AddUser({fileList:this.data.fileList,name:this.data.username,tel:this.data.phone,role_id:this.data.ruleForm.role_relation_real,project_id:this.data.ruleForm.relation_real}).then(res=>{
        var pages = getCurrentPages(); //当前页面
        var beforePage = pages[pages.length - 2]; //前一页
        wx.navigateBack({
          success: function () {
            beforePage.onPullDownRefresh(); // 执行前一个页面的onLoad方法
          }
        });
      })
    }
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '数据加载中',
    })

    projectList({type:3}).then(res=>{
      console.log(res)
      this.setData({
        // relationOption:res.data.data.map(item => {
        //   return { text: item.project_name, value: item.id };
        // }),
        project_list: res.data.data
      })
      wx.hideLoading({
        complete: (res) => {},
      })
      wx.hideNavigationBarLoading(); //完成停止加载图标
      wx.stopPullDownRefresh();
      
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})